package mx.forms;

import netscape.javascript.JSObject;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Worker.State;
import javafx.event.EventHandler;
import javafx.geometry.HPos;
import javafx.geometry.VPos;
import javafx.scene.Node;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebEvent;
import javafx.scene.web.WebView;

public class Browser extends Region {
    final WebView browser = new WebView();
    final WebEngine webEngine = browser.getEngine();
     
    public Browser() {
        //apply the styles
        getStyleClass().add("browser");
        // load the web page
        //webEngine.load("http://www.baidu.com");
        //add the web view to the scene
        getChildren().add(browser);
        
        webEngine.setOnStatusChanged(
                new EventHandler<WebEvent<String>>() {
                    public void handle(WebEvent<String> ev) {
                    	String s = ev.getData();
                    	if (! "_java_".equals(s)) return;
                    	
                    	JSObject win = (JSObject) webEngine.executeScript("window");
                    	Java java = new Java(webEngine);
                    	win.setMember("_java_", java);
                    	//System.out.println("accept!");
                    }
                });
    }
    
    public void loadUrl(String url) {
    	this.webEngine.load(url);
    }
    
    public void loadContent(String content) {
    	this.webEngine.loadContent(content);
    }
    
    private Node createSpacer() {
        Region spacer = new Region();
        HBox.setHgrow(spacer, Priority.ALWAYS);
        return spacer;
    }
 
    @Override protected void layoutChildren() {
        double w = getWidth();
        double h = getHeight();
        layoutInArea(browser,0,0,w,h,0, HPos.CENTER, VPos.CENTER);
    }
 
    @Override protected double computePrefWidth(double height) {
        return 900;
    }
 
    @Override protected double computePrefHeight(double width) {
        return 600;
    }
}
